import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QMessageBox
from PySide6.QtGui import QIcon
from PySide6.QtCore import QThread, Signal, QObject
from ui.Blueoco import Ui_BlueocoSpider
from serve import ProductSpider


class SpiderWorker(QObject):
    finished = Signal()
    log_message = Signal(str)

    def __init__(self, base_url, max_products, extract_image, extract_description, extract_price, save_format):
        super().__init__()
        self.base_url = base_url
        self.max_products = max_products
        self.extract_image = extract_image
        self.extract_description = extract_description
        self.extract_price = extract_price
        self.save_format = save_format

    def run_spider(self):
        def logger(message):
            self.log_message.emit(message)

        spider = ProductSpider(self.base_url, self.max_products, self.extract_image, self.extract_description,
                               self.extract_price, self.save_format, logger)
        spider.run()
        self.finished.emit()


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_BlueocoSpider()
        self.ui.setupUi(self)
        self.setWindowIcon(QIcon(":/Logo/Logo.svg"))
        self.setFixedSize(self.size())

        # 连接按钮点击事件到启动爬虫的方法
        self.ui.startButton.clicked.connect(self.start_spider)

    def start_spider(self):
        # 禁用开始按钮以防止重复点击
        self.ui.startButton.setEnabled(False)

        # 获取表单参数
        base_url = self.ui.urlEdit.text()
        max_products = self.ui.maxSpin.value()
        extract_image = self.ui.picCheck.isChecked()
        extract_description = self.ui.nameCheck.isChecked()
        extract_price = self.ui.priceCheck.isChecked()
        save_format = self.ui.saveCombo.currentText().lower()

        # 验证基础 URL 是否为空
        if not base_url:
            QMessageBox.warning(self, "输入错误", "请输入基础URL。")
            self.ui.startButton.setEnabled(True)  # 重新启用按钮
            return

        if not base_url.startswith('https://www.blueoco.com/') :
            QMessageBox.warning(self, "输入错误", "请输入开头为 https://www.blueoco.com/ 的网址")
            self.ui.startButton.setEnabled(True)  # 重新启用按钮
            return

        # 创建并启动爬虫线程
        self.worker = SpiderWorker(base_url, max_products, extract_image, extract_description, extract_price,
                                   save_format)
        self.thread = QThread()
        self.worker.moveToThread(self.thread)
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)
        self.worker.finished.connect(self.on_spider_finished)
        self.worker.log_message.connect(self.log_output)

        self.thread.started.connect(self.worker.run_spider)
        self.thread.start()

    def on_spider_finished(self):
        self.ui.startButton.setEnabled(True)  # 爬虫线程完成后重新启用按钮

    def log_output(self, message):
        self.ui.logEdit.appendHtml(message)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
